"""
用户业务相关工具包
"""
import string
import random
from typing import Optional
from application.config import CAPTCHA_KEY
from application.entity.UserEntity import UserSearchOut
from application.mapper.UserMapper import UserMapper
from application.model.UserModel import UserModel
from application.util.RedisUtil import RedisUtil
from application.util.StringUtil import sha1_encode, md5_encode

# 实例化redis客户端
redis_client: RedisUtil = RedisUtil()


def encode_password(password: str) -> str:
    """
    密码加密
    :param password: 密码
    :return: 加密后的密码
    """
    # sha1(md5)
    return sha1_encode(md5_encode(password))


async def generate_username(length: int = 10) -> str:
    """
    生成随机用户名
    :param length:
    :return:
    """
    characters = string.ascii_letters + string.digits
    random_part = "".join(random.choice(characters) for _ in range(length))
    username = "bb_" + random_part
    # 如果用户名已存在，则重新生成
    if await UserMapper.orm_model.exists(username=username):
        return await generate_username(length=length)
    return username


def verify_captcha(key: str, captcha: str) -> bool:
    """
    验证验证码
    :param key: 手机号/邮箱
    :param captcha: 验证码
    :return:
    """
    result: Optional[str] = redis_client.get_value(key=CAPTCHA_KEY + key)
    if result is None or captcha != result:
        return False
    # 验证码验证成功后删除
    redis_client.delete_by_key(key=CAPTCHA_KEY + key)
    return True


async def to_user_search_out(user_model: UserModel) -> UserSearchOut:
    """
    转换为用户搜索/简单输出实体
    :param user_model: 搜索/简单输出实体
    :return:
    """
    return UserSearchOut(**user_model.to_dict())
